package logic

import (
	"context"
	"go-zero-library-server/common/R"
	"go-zero-library-server/service/book/cmd/api/internal/svc"
	"go-zero-library-server/service/book/cmd/api/internal/types"
	"go-zero-library-server/service/lend/cmd/rpc/lend"

	"github.com/tal-tech/go-zero/core/logx"
)

type GetBookByNameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetBookByNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) GetBookByNameLogic {
	return GetBookByNameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetBookByNameLogic) GetBookByName(req types.GetBookByNameReq) (*types.Reply, error) {
	bookList, err := l.svcCtx.BookModel.GetBookByName(req.Name)
	if err != nil {
		return nil, err
	}
	var bookDatas []types.BookData
	for _,e := range bookList{
		isLendReply, err := l.svcCtx.LendRpc.IsLend(l.ctx, &lend.BookIdReq{Id: uint64(e.ID)})
		if err != nil {
			return nil, err
		}
		bookDatas = append(bookDatas, types.BookData{Id: e.ID,Name: e.Name,Image: e.Image,IsLend: isLendReply.IsLend})
	}
	return &types.Reply{Code: R.OK().Code,Data: map[string]interface{}{"bookDatas": bookDatas} ,Msg: R.OK().Msg}, nil
}
